/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.entity;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author DTIT
 */
@Entity
@Table(name = "uzer")
public class Uzer implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;
  @Column(unique = true)
  private String username;
  private String password;
  private boolean deleted;
  @ElementCollection(targetClass = Role.class)
  @Enumerated(EnumType.STRING)
  @CollectionTable(name = "user_role")
  @Column(name = "role_id")
  private Collection<Role> roles = new ArrayList<>();
  private String timeZone;

  public String getTimeZone() {
    return timeZone;
  }
  
  public TimeZone getTimeZoneObj() {
    return TimeZone.getTimeZone(timeZone);
  }

  public void setTimeZone(String timeZone) {
    this.timeZone = timeZone;
  }
  
  public void setRoles(Collection<Role> roles) {
    this.roles = roles;
  }
  
  public void addRoles(Role role) {
    roles.add(role);
  }

  public boolean inRole(Role role) {
    return roles.contains(role);
  }

  public Collection<Role> getRoles() {
    return roles;
  }

  public boolean isDeleted() {
    return deleted;
  }

  public void setDeleted(boolean deleted) {
    this.deleted = deleted;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return username;
  }

  public void setUsername(String userName) {
    this.username = userName;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      digest.update(password.getBytes("UTF-8"));
      byte[] hash = digest.digest();
      BigInteger bigInt = new BigInteger(1, hash);
      this.password = bigInt.toString(16);
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
      Logger.getLogger(Uzer.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
